package com.itboye.sunsun.luntan;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Spanned;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.sunsun.R;
import com.itboye.sunsun.adapter.TieZiCommentAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.LunTanCommontBean;
import com.itboye.sunsun.beans.LunTanCommontBean.GenTieItemBean;
import com.itboye.sunsun.constants.NetPublicConstant;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.controller.LoginController;
import com.itboye.sunsun.custome.FaceInputView;
import com.itboye.sunsun.custome.FaceInputView.Face;
import com.itboye.sunsun.custome.FaceInputView.OnFaceClickListener;
import com.itboye.sunsun.custome.XExpandableListView;
import com.itboye.sunsun.custome.XExpandableListView.IXListViewListener;
import com.itboye.sunsun.dialog.WaitDialog;
import com.itboye.sunsun.luntan.FaBiaoTieZiActivity.PhotoSelect;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.person.ui.NewsDetailShareFragment;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.uesrinfo.TieZiQuanXianManager;
import com.itboye.sunsun.utils.DensityUtil;
import com.itboye.sunsun.utils.ImageCompress;
import com.itboye.sunsun.utils.PhotoSelectFragment;
import com.itboye.sunsun.utils.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.sunsun.utils.CameraPopupWindow;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.utils.Spanned2String;
import com.itboye.sunsun.utils.Utils;
import com.itboye.sunsun.utils.XImageLoader;
import com.itboye.sunsun.utils.XPicasso;
import com.itboye.sunsun.volley.ImageCompressAndUpload;
import com.itboye.sunsun.volley.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.pobing.uilibs.extend.component.dialog.ImageViewerDialog;

//

public class TieZiDetailActivity extends BaseActivity {

	XExpandableListView xlistview;
	ImageView shoucang;

	// LunTanItemBean lunTanItemBean;
	BaseExpandableListAdapter adapter;
	LunTanCommontBean commontList = new LunTanCommontBean();
	private int pageNum = 1;
	ViewGroup bottom;
	EditText input;
	View headerView;
	ViewGroup imgContainer;
	String fid;
	String tid;
	View addImg;
	View addEmoj;
	Integer gentiePosition = null;
	LinearLayout selectImgContainer;
	// boolean isGentie=true;
	WaitDialog waitDialog;
	View jubao;
	String pid = "";
	String beiJuBaoId = "";
	String beiJuBaoUserName = "";

	String authorId = "";

	ImageView share;
	View jiajing;
	View zhiding;
	View delete;
	FaceInputView faceInputView;
	HorizontalScrollView horizontalScrollView;
	// 点赞
	private String isLove;
	protected String content;
	private String title;
	boolean isLoadMore=false;

	public static int WIDTH;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		setContentView(R.layout.activity_tiezi_xiangqing);

		IntentFilter filter2 = new IntentFilter("changegroup");
		registerReceiver(broadcastReceiver2, filter2);
		showProgressDialog("数据加载中，请稍后", true);
		xlistview.setGroupIndicator(null);
		setStatusBarColor(R.color.top_blue);
		WIDTH=getWindowManager().getDefaultDisplay().getWidth();
		fid = getIntent().getStringExtra("fid");
		tid = getIntent().getStringExtra("tid");
		//
		System.out.println(">>>>>>>>>>>>>>>>tid"
				+ tid
				+ "uid"
				+ SPUtils.get(getApplicationContext(), null,
						SPContants.USER_ID, ""));
		authorId = getIntent().getStringExtra("author_id");
		// //
		// // fid="1";
		// // tid="1";
		shoucang.setEnabled(false);
		// TODO Auto-generated method stub

		headerView = getLayoutInflater().inflate(
				R.layout.item_tiezi_detail_headerview, xlistview, false);
		xlistview.addHeaderView(headerView);
		adapter = new TieZiCommentAdapter(commontList, TieZiDetailActivity.this);

		xlistview.setAdapter(adapter);

		jiajing = headerView.findViewById(R.id.jiajing);
		zhiding = headerView.findViewById(R.id.zhiding);
		jiajing.setTag(false);
		zhiding.setTag(false);
		imgContainer = (ViewGroup) headerView.findViewById(R.id.imgContainer);
		headerView.findViewById(R.id.zan).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// onBBsPraiseClick(v);
						LoginController.onBBSPraiseClick(
								TieZiDetailActivity.this, null);
					}
				});

		delete = headerView.findViewById(R.id.delete);
		getYuanTieInfo();
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			huifu();
		};
	};
	protected int size;

	BroadcastReceiver broadcastReceiver2 = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			size = intent.getIntExtra("size", 0);
			huifu();
			getYuanTieInfo();
		};
	};

	public void getYuanTieInfo() {

		MyJsonRequest.Builder<GenTieItemBean> builder = new MyJsonRequest.Builder<GenTieItemBean>()
				.apiVer("100")
				.typeKey("BY_ForumThread_detail")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))

				.requestListener(new XRequestListener<GenTieItemBean>() {

					@Override
					public void onResponse(GenTieItemBean bean) {
						isLove = bean.getIsLove();
						if (Integer.parseInt(isLove) == 1) {
							((ImageView) headerView.findViewById(R.id.zan))
									.setImageResource(R.drawable.dianzan);
						} else {
							((ImageView) headerView.findViewById(R.id.zan))
									.setImageResource(R.drawable.dianzan_unselect);
						}
						fid = bean.getFid();
						content = bean.getSubject().toString();
						initView();
						if (!"1".equals(bean.getStatus())) {
							Toast.makeText(getApplicationContext(), "原贴已删除", 1)
									.show();
							try {
								closeProgressDialog();
							} catch (Exception e) {
								// TODO: handle exception
							}
							return;
						}
						if (bean.getFavorite() == 1) {
							shoucang.setImageResource(R.drawable.ic_yishoucang);
							shoucang.setTag(true);
						} else {
							shoucang.setTag(false);
						}
						shoucang.setEnabled(true);

						if (bean.getUserInfo() != null) {
							((TextView) headerView.findViewById(R.id.name))
									.setText(bean.getUserInfo().getNickname());
							if (bean.getUserInfo().getHead() == ""
									|| bean.getUserInfo().getHead() == null) {
								Bitmap bitmap = BitmapFactory
										.decodeResource(getResources(),
												R.drawable.defaultimage);
								((ImageView) headerView.findViewById(R.id.head))
										.setImageBitmap(bitmap);
							} else {

								if (!bean.getUserInfo().getHead()
										.startsWith("http")) {
									XImageLoader.load(
											NetPublicConstant.IMAGE_URL
													+ bean.getUserInfo()
															.getHead(),
											(ImageView) headerView
													.findViewById(R.id.head));
								} else {
									XImageLoader.load(bean.getUserInfo()
											.getHead(), (ImageView) headerView
											.findViewById(R.id.head));
								}
								// XImageLoader.load(NetPublicConstant.IMAGE_URL
								// + bean.getUserInfo().getHead(),
								// );
							}

						}
						title = bean.getSubject().toString();
						((TextView) headerView.findViewById(R.id.title))
								.setText(bean.getSubject());
						if ("1".equals(bean.getDigest())) {
							jiajing.setVisibility(View.VISIBLE);
							jiajing.setTag(true);
						} else {
							jiajing.setTag(false);
						}

						if ("1".equals(bean.getStick())) {
							zhiding.setVisibility(View.VISIBLE);
							zhiding.setTag(true);
						} else {
							zhiding.setTag(false);
						}

						if (TieZiQuanXianManager.canDeleteBBs(fid, bean
								.getUserInfo().getId())) {

							delete.setVisibility(View.VISIBLE);
							delete.setOnClickListener(new OnClickListener() {

								@Override
								public void onClick(View v) {

									MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
											.apiVer("100")
											.typeKey("BY_ForumThread_delete")
											.param("tid", tid)

											.param("uid",
													(String) SPUtils
															.get(getApplicationContext(),
																	null,
																	SPContants.USER_ID,
																	""))
											.requestListener(
													new XRequestListener<String>() {

														@Override
														public void onResponse(
																String orderBean) {

															Toast.makeText(
																	getApplicationContext(),
																	"删除成功", 1)
																	.show();
															Intent intent = new Intent(
																	"refresh");
															sendBroadcast(intent);
															// intent.putExtra(
															// "fid", fid);
															// setResult(102,
															// intent);
															finish();
														}
													})
											.errorListener(
													new XErrorListener() {

														@Override
														public void onErrorResponse(
																Exception exception,
																int code,
																String msg) {

														}
													});

									MyJsonRequest<String> request = builder
											.build();
									HttpRequest.getDefaultRequestQueue().add(
											request);
								}
							});
						} else {
							delete.setVisibility(View.GONE);
						}

						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
						pullDown();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<GenTieItemBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	// 输入表情需要
	ImageGetter imageGetter = new ImageGetter() {
		@Override
		public Drawable getDrawable(String source) {
			int id = Integer.parseInt(source);
			Drawable d = getResources().getDrawable(id);
			d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
			return d;
		}
	};
	protected NewsDetailShareFragment fragment;

	private void initView() {
		if (TieZiQuanXianManager.canAddJingHua(fid)) {
			jiajing.setVisibility(View.VISIBLE);
			jiajing.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					jiajing.setEnabled(false);
					final String flag = (Boolean) jiajing.getTag() ? "0" : "1";
					MyJsonRequest<String> request = new MyJsonRequest.Builder<String>()
							.apiVer("100")
							.typeKey("BY_ForumThread_digest")
							.param("uid",
									(String) SPUtils.get(
											getApplicationContext(), null,
											SPContants.USER_ID, ""))
							.param("tid", tid).param("digest_value", flag)
							.requestListener(new XRequestListener<String>() {

								@Override
								public void onResponse(String arg0) {
									jiajing.setEnabled(true);
									if ("0".equals(flag)) {
										jiajing.setTag(false);
										Toast.makeText(getApplicationContext(),
												"取消加精成功", 1).show();
									} else {
										jiajing.setTag(true);
										Toast.makeText(getApplicationContext(),
												"加精成功", 1).show();
									}
								}
							}).errorListener(new XErrorListener() {

								@Override
								public void onErrorResponse(
										Exception exception, int code,
										String msg) {
									jiajing.setEnabled(true);
									if ("0".equals(flag)) {
										Toast.makeText(getApplicationContext(),
												"取消加精失败", 1).show();
									} else {
										Toast.makeText(getApplicationContext(),
												"加精失败", 1).show();
									}
								}
							}).build();
					HttpRequest.getDefaultRequestQueue().add(request);
				}
			});
		}
		//
		if (TieZiQuanXianManager.canTopBBs(fid)) {
			zhiding.setVisibility(View.VISIBLE);
			zhiding.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					zhiding.setEnabled(false);
					final String flag = (Boolean) zhiding.getTag() ? "0" : "1";
					MyJsonRequest<String> request = new MyJsonRequest.Builder<String>()
							.apiVer("100")
							.typeKey("BY_ForumThread_stick")
							.param("uid",
									(String) SPUtils.get(
											getApplicationContext(), null,
											SPContants.USER_ID, ""))
							.param("tid", tid).param("stick_value", flag)
							.requestListener(new XRequestListener<String>() {

								@Override
								public void onResponse(String arg0) {
									zhiding.setEnabled(true);
									if ("0".equals(flag)) {
										zhiding.setTag(false);
										Toast.makeText(getApplicationContext(),
												"取消置顶成功", 1).show();
									} else {
										zhiding.setTag(true);
										Toast.makeText(getApplicationContext(),
												"置顶成功", 1).show();
									}
								}
							}).errorListener(new XErrorListener() {

								@Override
								public void onErrorResponse(
										Exception exception, int code,
										String msg) {
									zhiding.setEnabled(true);
									if ("0".equals(flag)) {
										Toast.makeText(getApplicationContext(),
												"取消置顶失败", 1).show();
									} else {
										Toast.makeText(getApplicationContext(),
												"置顶失败", 1).show();
									}
								}
							}).build();
					HttpRequest.getDefaultRequestQueue().add(request);
				}
			});
		}

		findViewById(R.id.back).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		xlistview.setPullRefreshEnable(true);
		xlistview.setPullLoadEnable(true);
		xlistview.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				pageNum = 1;
				pullDown();
			}

			@Override
			public void onLoadMore() {
				pageNum++;
				pullUp();
			}

		});

		addEmoj.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				v.setSelected(!v.isSelected());
				if (faceInputView == null) {
					faceInputView = new FaceInputView(getApplicationContext());
					bottom.addView(faceInputView);
					faceInputView.setOnClickListener(new FaceInputListenr());
				}
				if (v.isSelected()) {
					if (bottom.getChildCount() == 2) {
						bottom.getChildAt(1).setVisibility(View.GONE);
					} else if (bottom.getChildCount() == 3) {
						bottom.getChildAt(1).setVisibility(View.GONE);
						bottom.getChildAt(2).setVisibility(View.GONE);
					}

					InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
					inputMethodManager.hideSoftInputFromWindow(
							input.getWindowToken(), 0);
					faceInputView.setVisibility(View.VISIBLE);
					addImg.setSelected(false);

				} else {
					faceInputView.setVisibility(View.GONE);

				}
			}
		});

		addImg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (selectImgContainer == null) {
					horizontalScrollView = (HorizontalScrollView) getLayoutInflater()
							.inflate(R.layout.item_pinglun_img_select, bottom,
									false);
					bottom.addView(horizontalScrollView);
					selectImgContainer = (LinearLayout) horizontalScrollView
							.getChildAt(0);

					selectImgContainer.getChildAt(0).setOnClickListener(
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									mCameraPopupWindow = new CameraPopupWindow(
											TieZiDetailActivity.this,
											onclicklister);
									mCameraPopupWindow.showAtLocation(
											selectImgContainer.getChildAt(0),
											Gravity.BOTTOM
													| Gravity.CENTER_HORIZONTAL,
											0, 0);

								}
							});

				}
				addImg.setSelected(!addImg.isSelected());
				if (addImg.isSelected()) {
					if (bottom.getChildCount() == 2) {
						bottom.getChildAt(1).setVisibility(View.GONE);
					} else if (bottom.getChildCount() == 3) {
						bottom.getChildAt(1).setVisibility(View.GONE);
						bottom.getChildAt(2).setVisibility(View.GONE);
					}
					((View) selectImgContainer.getParent())
							.setVisibility(View.VISIBLE);
					addEmoj.setSelected(false);
				} else {
					((View) selectImgContainer.getParent())
							.setVisibility(View.GONE);
				}
			}

		});

		
		findViewById(R.id.send).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				if(Utils.isFastClick()){
					return;
				}else
				if (input.getText().toString() == null) {
					Toast.makeText(App.ctx, "请输入跟帖内容", 0).show();
					return;
				}
				LoginController.onBBSCommentClick(TieZiDetailActivity.this,
						null);

			}
		});

		shoucang.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				LoginController.onBBSCollectClick(TieZiDetailActivity.this, v);
			}
		});

		jubao.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LoginController.onBBSJuBaoClick(TieZiDetailActivity.this, null);
			}
		});
		share.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(final View v) {
				fragment = new NewsDetailShareFragment();
				Bundle args = new Bundle();
				args.putString("content", content);
				args.putString("title", title);
				fragment.setArguments(args);
				fragment.show(getSupportFragmentManager(),
						NetPublicConstant.secondUrl+"/Webview/User/download");
			}
		});
	}

	private CameraPopupWindow mCameraPopupWindow;
	// 使用相机拍照
	private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 110;
	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				if (selectImgContainer.getChildCount() > 6) {
					Toast.makeText(TieZiDetailActivity.this, "最多上传6张照片", 0)
							.show();
					mCameraPopupWindow.dismiss();
					return;
				}
				/**
				 * 打开照相机
				 */
				String state = Environment.getExternalStorageState();
				if (state.equals(Environment.MEDIA_MOUNTED)) {

					/**
					 * 打开照相机
					 */
					picture_name = android.text.format.DateFormat.format(
							"yyyyMMdd_hhmmss",
							Calendar.getInstance(Locale.CHINA))
							+ ".jpg";
					File file = new File("/sdcard/Image/");
					file.mkdirs();// 创建文件夹
					fileName = "/sdcard/Image/" + picture_name;
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(fileName)));
					startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);

				} else {
					Toast.makeText(TieZiDetailActivity.this, "请确认已经插入SD卡", 0)
							.show();
				}
				break;
			case R.id.pick_image:
				new PhotoSelectFragment(photoListenr,
						6 - selectImgContainer.getChildCount() + 1).show(
						getSupportFragmentManager(), null);

				mCameraPopupWindow.dismiss();
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};
	private String picture_name;
	private String fileName;
	private View v;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
			if (resultCode == RESULT_OK) {
				Bitmap bit = BitmapFactory.decodeFile(fileName);
				int degree = ImageCompress.readPictureDegree(fileName);
				if (degree <= 0) {
				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);
				}
				saveImage(bit, new File(fileName));
			} else {
				Toast.makeText(this, "拍照取消", 0).show();
			}
			mCameraPopupWindow.dismiss();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void saveImage(Bitmap data, File file) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			return;
		}
		FileOutputStream b = null;
		try {
			b = new FileOutputStream(fileName);
			data.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			v = LayoutInflater.from(getApplicationContext()).inflate(
					R.layout.item_fabiao_tiezi_image_select, null);

			v.setLayoutParams(new LayoutParams(DensityUtil.dip2px(80),
					LayoutParams.MATCH_PARENT));
			((ImageView) v.findViewById(R.id.img)).setImageBitmap(data);
			v.setTag(fileName);
			selectImgContainer.addView(v,
					selectImgContainer.getChildCount() - 1);

			v.findViewById(R.id.del).setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View vvv) {
					selectImgContainer.removeView(v);
					arrayList.remove(v);
				}
			});
			arrayList.add(v);
		} catch (Exception e) {
		}
	}

	public void onJuBaoCLick() {
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("100")
				.typeKey("BY_CoreReport_bbsReport")
				.param("tid", tid)
				.param("fid", fid)
				.param("pid", pid)
				.param("uid", beiJuBaoId)
				.param("username", beiJuBaoUserName)
				.param("op_uid",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String bean) {

						Toast.makeText(getApplicationContext(), "举报成功", 1)
								.show();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {

					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void onBBsPraiseClick() {
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("101")
				.typeKey("BY_ForumThread_like")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String orderBean) {
						/***
						 * 当islove为0时是已经点赞成功了的否则是点赞过了的无需点赞
						 */
						if (isLove == "0") {
							Toast.makeText(getApplicationContext(), orderBean,
									1).show();
						} else {
							Toast.makeText(getApplicationContext(), orderBean,
									1).show();
						}
						((ImageView) headerView.findViewById(R.id.zan))
								.setImageResource(R.drawable.dianzan);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(getApplicationContext(), msg, 1).show();
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	ArrayList<View> arrayList = new ArrayList<>();

	public void onBBsCollectClick(final View v) {
		// TODO Auto-generated method stub
		v.setEnabled(false);
		MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
				.apiVer("100")
				.typeKey("BY_ForumThread_favorites")
				.param("tid", tid)
				.param("uid",
						SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.param("favorite_value", (Boolean) v.getTag() ? 0 : 1)
				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String orderBean) {
						v.setTag(!(Boolean) v.getTag());
						if ((Boolean) v.getTag()) {
							shoucang.setImageResource(R.drawable.ic_yishoucang);
						} else {
							shoucang.setImageResource(R.drawable.ic_tiezi_shoucang);

						}
						v.setEnabled(true);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						v.setEnabled(true);
					}
				});

		MyJsonRequest<String> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	PhotoSelectListener photoListenr = new PhotoSelectListener() {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {

				Bitmap bit = BitmapFactory.decodeFile(string);
				int degree = ImageCompress.readPictureDegree(string);
				if (degree <= 0) {
				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);
				}
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					return;
				}
				FileOutputStream b = null;
				try {
					b = new FileOutputStream(string);
					bit.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				
				/**
				 * FileOutputStream b = null;
				try {
					b = new FileOutputStream(file);
					if(b!=null){
						DebugLog.v("FileOutputStream",b);
					}else{
						bit.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
					}
					
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
				 */
				// saveImage(bit, new File(string));

				v = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.item_fabiao_tiezi_image_select, null);

				v.setLayoutParams(new LayoutParams(DensityUtil.dip2px(80),
						LayoutParams.MATCH_PARENT));

				((ImageView) v.findViewById(R.id.img)).setImageBitmap(bit);
				// XImageLoader.load("file://" + string,
				// (ImageView) v.findViewById(R.id.img));
				v.setTag(string);
				selectImgContainer.addView(v,
						selectImgContainer.getChildCount() - 1);

				v.findViewById(R.id.del).setOnClickListener(
						new OnClickListener() {

							@Override
							public void onClick(View vvv) {
								selectImgContainer.removeView(v);
								arrayList.remove(v);
							}
						});
				arrayList.add(v);

			}
		}
	};

	public void onCommentClick() {
		if (!TieZiQuanXianManager.canPublishMessage(fid)) {
			Toast.makeText(getApplicationContext(), "无权发帖", 1).show();
			return;
		}
		if (gentiePosition != null && commontList.getList().size() > 0) {
			// 评论
			MyJsonRequest.Builder<String> builder = new MyJsonRequest.Builder<String>()
					.apiVer("100")
					.typeKey("BY_ForumPost_replyPost")
					.param("tid", tid)
					.param("pid",
							commontList.getList().get(gentiePosition).getPid())
					.param("author",
							(String) SPUtils.get(getApplicationContext(), null,
									SPContants.NICK, ""))
					.param("author_id",
							(String) SPUtils.get(getApplicationContext(), null,
									SPContants.USER_ID, ""))
					.param("comment", Spanned2String.parse(input.getText()))
					.requestListener(new XRequestListener<String>() {

						@Override
						public void onResponse(String orderBean) {
							input.setText(null);
							Toast.makeText(getApplicationContext(), "评论成功", 1)
									.show();
							pageNum=1;
							pullDown();
							huifu();
						}
					}).errorListener(new XErrorListener() {

						@Override
						public void onErrorResponse(Exception exception,
								int code, String msg) {
							Toast.makeText(getApplicationContext(), "评论失败", 1)
									.show();
						}
					});

			MyJsonRequest<String> request = builder.build();
			HttpRequest.getDefaultRequestQueue().add(request);
		} else {
			if (selectImgContainer == null
					|| selectImgContainer.getChildCount() == 1) {
				sendToServer(null);
				return;
			}
			// 回帖
			if (waitDialog == null) {
				waitDialog = new WaitDialog();
			}
			waitDialog.show(getSupportFragmentManager(), null);
			final Toast toast = Toast.makeText(getApplicationContext(),
					"图片上传失败", 1);
			final List<String> uploadedUrl = new ArrayList<>();
			for (int i = 0; i < selectImgContainer.getChildCount() - 1; i++) {

				ImageCompressAndUpload.getInstance().execute(
						(String) selectImgContainer.getChildAt(i).getTag(),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);

								if (uploadedUrl.size() == selectImgContainer
										.getChildCount() - 1) {
									if (waitDialog != null) {
										waitDialog.dismiss();
									}

									sendToServer(uploadedUrl);
								}
							}

							@Override
							public void OnError(String resultData) {
								if (waitDialog != null) {
									waitDialog.dismiss();
								}

								toast.show();
							}
						});

			}

		}
	}

	boolean isAddHeader = false;
	private int gentieSize;

	// 回帖
	protected void sendToServer(List<String> uploadedUrl) {
		MyJsonRequest.Builder<Object> builder = new MyJsonRequest.Builder<Object>()
				.apiVer("100")
				.typeKey("BY_ForumPost_reply")
				.param("fid", fid)
				.param("tid", tid)
				.param("author",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.NICK, ""))
				.param("author_id",
						(String) SPUtils.get(getApplicationContext(), null,
								SPContants.USER_ID, ""))
				.param("message", Spanned2String.parse(input.getText()))

				.requestListener(new XRequestListener<Object>() {

					@Override
					public void onResponse(Object orderBean) {

						// GenTieItemBean bean = new GenTieItemBean();
						// bean.setDateline(System.currentTimeMillis() + "");
						// bean.setMessage(input.getText());
						// bean.setSubject(input.getText());
						// commontList.getList().add(bean);
						//
						// adapter.notifyDataSetChanged();
						Toast.makeText(getApplicationContext(), "回帖成功", 1)
								.show();
						pageNum=1;
						pullDown();
						for (int i = 0; i < arrayList.size(); i++) {

							selectImgContainer.removeView(arrayList.get(i));
						}
						input.setText(null);
						((View) selectImgContainer.getParent())
								.setVisibility(View.GONE);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						Toast.makeText(getApplicationContext(), "回帖失败", 1)
								.show();
					}
				});

		if (uploadedUrl != null && uploadedUrl.size() > 0) {
			StringBuilder sb = new StringBuilder();
			sb.append(uploadedUrl.get(0));
			for (int i = 1; i < uploadedUrl.size(); i++) {
				sb.append(",").append(uploadedUrl.get(i));
			}

			builder.param("attachments", sb.toString());

		}
		MyJsonRequest<Object> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private class FaceInputListenr implements OnFaceClickListener {

		@Override
		public void selectedFace(Face face) {
			int id = face.faceId;
			if (id == R.drawable.ic_face_delete_normal)// 删除按钮
			{
				int index = input.getSelectionStart();
				if (index == 0)
					return;
				Editable editable = input.getText();
				editable.delete(index - 1, index);// 删除最后一个字符或表情
			} else {
				input.append(Html.fromHtml("<img src='" + id + "'/>",
						imageGetter, null));// 添加表情
			}
		}

	}

	protected void pullUp() {
		System.out.println(fid + ":" + tid + ":" + pageNum);
		MyJsonRequest.Builder<LunTanCommontBean> builder = new MyJsonRequest.Builder<LunTanCommontBean>()
				.param("fid", fid).param("tid", tid).apiVer("100")
				.param("curpage", "" + pageNum).typeKey("BY_ForumPost_query")
				.requestListener(new XRequestListener<LunTanCommontBean>() {

					@Override
					public void onResponse(LunTanCommontBean orderBean) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
							updateCommentList(orderBean);
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
					}
				});

		MyJsonRequest<LunTanCommontBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	protected void addHeaderImageAndContent(GenTieItemBean genTieItemBean) {
		((TextView) headerView.findViewById(R.id.content))
				.setText(genTieItemBean.getMessage());
		((TextView) headerView.findViewById(R.id.time)).setText(genTieItemBean
				.getDatelineShow());
		final List<String> imgs = genTieItemBean.getImg();
		if (imgs != null) {
			int h = DensityUtil.dip2px(170);
			int padd = DensityUtil.dip2px(8);
			for (int i = 0; i < imgs.size(); i++) {
				String string = imgs.get(i);
				ImageView imageView = new ImageView(getApplicationContext());
				LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
						getWindowManager().getDefaultDisplay().getWidth(),
						LinearLayout.LayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(0, 5, 0, 5);
				imageView.setLayoutParams(layoutParams);
				imageView.setScaleType(ScaleType.FIT_XY);
				imgContainer.addView(imageView);
				View divider = new View(getApplicationContext());
				imgContainer.addView(divider, new LayoutParams(padd, 1));
				XPicasso.loadImage(TieZiDetailActivity.this,imageView,NetPublicConstant.IMAGE_URL + string);

				final int ii = i;
				imageView.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						ImageViewerDialog dialog = new ImageViewerDialog(
								TieZiDetailActivity.this);
						String urls[] = new String[imgs.size()];
						for (int j = 0; j < urls.length; j++) {
							urls[j] = NetPublicConstant.IMAGE_URL + imgs.get(j);
						}
						dialog.setImageUrls(urls);
						dialog.show(ii);
					}
				});
			}
		}

	}

	private void pullDown() {
		MyJsonRequest.Builder<LunTanCommontBean> builder = new MyJsonRequest.Builder<LunTanCommontBean>()
				.param("fid", fid)
				.param("tid", tid)

				// .param("fid",lunTanItemBean.getFid())
				// .param("tid", lunTanItemBean.getTid())
				//
				.apiVer("100").param("curpage", "" + pageNum)

				.typeKey("BY_ForumPost_query")
				.requestListener(new XRequestListener<LunTanCommontBean>() {

					@Override
					public void onResponse(LunTanCommontBean bean) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						gentieSize = bean.getCount();
						if (bean.getCount() > 0 && bean.getList() != null
								) {
							try {

								pid = bean.getList().get(0).getPid();
								beiJuBaoId = bean.getList().get(0)
										.getAuthorId();
								beiJuBaoUserName = bean.getList().get(0)
										.getUserInfo().getUsername();
							} catch (Exception e) {
							}
							commontList.getList().clear();
							if (isAddHeader == false) {
								addHeaderImageAndContent(bean.getList().get(0));
								isAddHeader = true;
							}
							bean.getList().remove(0);
							updateCommentList(bean);

						}
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						xlistview.stopLoadMore();
						xlistview.stopRefresh();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<LunTanCommontBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}

	private void updateCommentList(LunTanCommontBean orderBean) {
		commontList.getList().addAll(orderBean.getList());
		List<GenTieItemBean> b = commontList.getList();
//		adapter=new TieZiCommentAdapter(commontList, TieZiDetailActivity.this);
		adapter.notifyDataSetChanged();
		for (int i = 0; i < b.size(); i++) {
			xlistview.expandGroup(i);
		}

	}

	public void onComment(int gentiePosition) {
		this.gentiePosition = gentiePosition;
		input.setHint("评论");
		addImg.setVisibility(View.GONE);
	}

	public void huifu() {
		gentiePosition = null;
		input.setHint("跟帖");
		addImg.setVisibility(View.VISIBLE);

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (addEmoj.isSelected()) {
				faceInputView.setVisibility(View.GONE);
				addEmoj.setSelected(false);
				return true;
			}

			if (addImg.isSelected()) {
				horizontalScrollView.setVisibility(View.GONE);
				addImg.setSelected(false);
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// unregisterReceiver(broadcastReceiver);
		unregisterReceiver(broadcastReceiver2);
	}
}
